import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:short_video_app/utils/color_util.dart';
import 'package:short_video_app/ui/widgets/custom_network_image.dart';

class VideoView extends StatefulWidget {
  /// 网络视频的 URL
  final String url;
  final String? cover;
  /// 是否自动播放
  final bool autoPlay;
  /// 是否循环播放
  final bool looping;
  /// 视频比例
  final double aspectRatio;
  final Widget? overlayUI;

  const VideoView({
    Key? key,
    required this.url,
    this.cover,
    this.autoPlay = false,
    this.looping = false,
    this.aspectRatio = 16 / 9,
    this.overlayUI
  }) : super(key: key);

  @override
  _VideoViewState createState() => _VideoViewState();
}

class _VideoViewState extends State<VideoView> {
  /// video_player 播放器的 Controller
  late VideoPlayerController _videoPlayerController;
  /// chewie 播放器的 Controller
  late ChewieController _chewieController;

  @override
  void initState() {
    super.initState();

    /// 初始化播放器 Controller
    _videoPlayerController = VideoPlayerController.network(widget.url);
    _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        aspectRatio: widget.aspectRatio,
        autoPlay: widget.autoPlay,
        looping: widget.looping,
        placeholder: CustomNetworkImage(
          url: widget.cover ?? "",
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        ),
        allowMuting: false,
        allowPlaybackSpeedChanging: false
    );
  }

  @override
  void dispose() {
    /// 销毁播放器 Controller
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    /// [MediaQuery] 媒体查询，使用静态函数 [of] 获取当前设备信息，[size] 为设备的逻辑像素
    double screenWidth = MediaQuery.of(context).size.width;
    double playerHeight = screenWidth / widget.aspectRatio;

    return Container(
      width: screenWidth,
      height: playerHeight,
      color: ColorsUtil.COLOR_999999,
      child: Chewie(
        controller: _chewieController,
      ),
    );
  }
}
